'use client';

import React, { useEffect, useState } from 'react';
import InfiniteMenu from '@/components/InfiniteMenu';
import { getNavigations, NavigationItem } from '@/lib/api';

export default function NavigationPage() {
  const [items, setItems] = useState<Array<{
    image: string;
    link: string;
    title: string;
    description: string;
  }>>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchNavigations = async () => {
      try {
        setLoading(true);
        const navigations = await getNavigations();
        
        const formattedItems = navigations.map((nav) => {
          let imageUrl = '';
          
          // 处理图片URL
          if (nav.image?.url) {
            // 如果URL已经是完整URL，直接使用
            if (nav.image.url.startsWith('http://') || nav.image.url.startsWith('https://')) {
              imageUrl = nav.image.url;
            } else {
              // 如果是相对路径，添加API基础URL
              const baseUrl = process.env.NEXT_PUBLIC_BACKEND_URL || 'https://server.illli.cc';
              imageUrl = `${baseUrl}${nav.image.url}`;
            }
          }
          
          return {
            image: imageUrl,
            link: nav.link,
            title: nav.title,
            description: nav.description
          };
        });
        
        setItems(formattedItems);
      } catch (err) {
        console.error('Failed to fetch navigations:', err);
        setError('获取导航数据失败');
      } finally {
        setLoading(false);
      }
    };

    fetchNavigations();
  }, []);

  return (
    <div className="bg-[#1e1b4b] w-full h-full min-h-screen">
      <div className="mx-auto pt-16 h-screen">
        {loading ? (
          <div className="flex justify-center items-center h-full">
            <div className="text-white text-xl">加载中...</div>
          </div>
        ) : error ? (
          <div className="flex justify-center items-center h-full">
            <div className="text-red-400 text-xl">{error}</div>
          </div>
        ) : (
          <div className="h-full w-full">
            <InfiniteMenu items={items} />
          </div>
        )}
      </div>
    </div>
  );
}